package yxy.game.pm2.active.command.levelpackage;

import yxy.apple.logger.Logger;
import yxy.cherry.data.bean.actgradepackage;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.active.module.ActiveModule_等级礼包;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ActiveMessage;
import yxy.game.pm2.message.ActiveMessage.ActLevelPackageDrawRewardRequest;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.module.CurrencyHandle;

import java.util.ArrayList;
import java.util.Collection;

@MessageType(proto = Command.ActLevelPackageDrawReward, classtype = ActiveMessage.ActLevelPackageDrawRewardRequest.class)
public class CMD_Active_等级礼包_DrawReward extends Command<ActLevelPackageDrawRewardRequest> {

	private static final Logger logger = Logger.create(CMD_Active_等级礼包_DrawReward.class);
	
	@Override
	public void execute(MessageSource messageSource, ActLevelPackageDrawRewardRequest request) throws Exception {
		String playercode = messageSource.getTag();
		int id = request.getId();
		ActiveMessage.ActLevelPackageDrawRewardResponse.Builder response = ActiveMessage.ActLevelPackageDrawRewardResponse.newBuilder();
		
		ActiveModule_等级礼包 am = ActiveModule_等级礼包.get(playercode,false);
		
		PlayerBean pb = PlayerBean.get(playercode);

		actgradepackage data = ActDataCenter.getData(id, actgradepackage.class, playercode);
		if (data == null) {
			send(messageSource, response, Result.DataError);
			return;
		}

		// 核对是否领取
		if (am.getDrawids().contains(id)) {
			send(messageSource, response, Result.ActHadGet);
			return;
		}

		// 核对等级
		if (pb.getLevel() < data.getCondition()) {
			send(messageSource, response, Result.ActCannotGet);
			return;
		}

		am.getDrawids().add(data.getId());
		am.set();

		ArrayList<Currency> curs = (ArrayList<Currency>) Currency.create(data.getRewardtype(), data.getRewardid(),
				data.getRewardnum());
		Collection<PackageMessage.Item> items = new CurrencyHandle().packItems(curs);

		response.addAllDisplay(items);

		// 下发道具
		new CurrencyHandle().addCurrency(playercode, CCReason.活动_等级礼包, curs);

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, ActiveMessage.ActLevelPackageDrawRewardResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
	
}
